<template>
  <view style="width: 100%">
    <up-cell-group :border="false">
      <up-cell
        :title="selectText"
        :isLink="true"
        :arrow-direction="direction"
        @click="show=true,direction='down'"
        :border="false"
      >
      </up-cell>
    </up-cell-group>
    <up-picker
      :show="show"
      :columns="[props.options]"
      :title="props.title"
      :keyName="props.labelKey"
      :defaultIndex="defaultSelect"
      @cancel="show=false,direction='right'"
      @confirm="confirm"
    >
    </up-picker>
  </view>
</template>

<script lang="ts" setup name="PickerRadio">

const props = defineProps({
  modelValue: {
    type: [String, Object, Number],
    default: null
  },
  //提示文字
  placeholder: {
    type: String,
    default: '请选择'
  },
  //选择框的数据
  options: {
    type: Array,
    default: () => []
  },
  //标题
  title: {
    type: String,
    default: '标题'
  },
  //自定义显示的文本字段
  labelKey: {
    type: String,
    default: 'label'
  },
  //自定义value字段
  valueKey: {
    type: String,
    default: 'value'
  }
});

const show = ref<boolean>(false);
const selectText = ref<string>(props.placeholder);
const emit = defineEmits(['update:modelValue']);
const defaultSelect = ref<Array<number>>([0]);
const direction = ref<string>('right');

const confirm = (d: any) => {
  selectText.value = d.value[0][props.lableKey];
  emit('update:modelValue', d.value[0][props.valueKey]);
  show.value = false;
  direction.value = 'right';
};

//设置默认选中项
watch(
  () => props.modelValue,
  (val) => {
    if (val && props.options.length > 0) {
      props.options.forEach((item: any, index: number) => {
        if (item[props.valueKey] == props.modelValue) {
          defaultSelect.value = [index];
          selectText.value = item[props.labelKey];
        }
      });
    }
  },
  { deep: true, immediate: true }
);
</script>

<style scoped lang="scss"></style>
